<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<input type="text" id="numId" />
		<input type="button" value="阶乘" onclick="cal()"/>
		<span id="resultId"></span>
		
		<script type="text/javascript">
			function cal() {
				var num = parseInt(document.getElementById("numId").value);
				var resultSpan = document.getElementById("resultId");
				
				if (isNaN(num)) {// 如果输入的不是一个数字isNaN返回true
					resultSpan.innerHTML = "<span style='color: red;'>输入的不是一个数字</span>";
					return;
				}
				
				if (num < 0) {
					resultSpan.innerHTML = "<span style='color: red;'>负数没有阶乘</span>";
					return;
				}
				
				if (num == 0) {
					resultSpan.innerHTML = 1;
				} else{
					var result = 1;
					// n!=n*(n-1)*...*3*2*1
					for (var i = num; i >= 1; i--) {
						result = result * i;
					}
					resultSpan.innerHTML = result;
				}
				
			}
		</script>
	</body>
</html>
